<?php
/* --------------------------------------------------------------
   callback.php 2012-05-21 gm
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2012 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------


/**
 * @version sofortueberweisung.de 4.2.0 - $Date: 2012-04-13 14:50:33 +0200 (Fri, 13 Apr 2012) $
 * @author Payment Network AG (integration@payment-network.com)
 * @link http://www.payment-network.com/
 *
 * @link http://www.xt-commerce.com
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 ***********************************************************************************
 * this file contains code based on:
 * (c) 2000 - 2001 The Exchange Project
 * (c) 2001 - 2003 osCommerce, Open Source E-Commerce Solutions
 * (c) 2003	 nextcommerce (account_history_info.php,v 1.17 2003/08/17); www.nextcommerce.org
 * (c) 2003 - 2006 XT-Commerce
 * Released under the GNU General Public License
 ***********************************************************************************
 *
 * $Id: callback.php 3795 2012-04-13 12:50:33Z rotsch $
 *
 */

chdir('../../');
require ('includes/application_top.php');

$language = $_SESSION['language'];

if ($language != 'german') {
	$language = 'english';
}

require_once('helperFunctions.php');
require('library/sofortLib.php');
require('library/sofortLib_classic_notification.inc.php');
include('lang/'.$language.'/modules/payment/sofort_sofortvorkasse.php');
include('lang/'.$language.'/modules/payment/sofort_sofortueberweisung.php');
include('lang/'.$language.'/modules/payment/sofort_sofortrechnung.php');
include('lang/'.$language.'/modules/payment/sofort_sofortlastschrift.php');
include('lang/'.$language.'/modules/payment/sofort_lastschrift.php');
include('lang/'.$language.'/modules/payment/sofort_ideal.php');
require_once('library/helper/class.invoice.inc.php');

if ($_GET['action'] == 'ideal') { //ideal
	list ($userid, $projectid) = explode(':', MODULE_PAYMENT_PNAG_IDEAL_CLASSIC_CONFIGURATION_KEY);
	$SofortLib_ClassicNotification = new SofortLib_ClassicNotification($userid, $projectid, MODULE_PAYMENT_PNAG_IDEAL_CLASSIC_NOTIFICATION_PASSWORD);
	$SofortLib_ClassicNotification->getNotification();
	
	if ($SofortLib_ClassicNotification->isError()) {
		exit($SofortLib_ClassicNotification->getError());
	}
	
	$transactionId = $SofortLib_ClassicNotification->getTransaction();
	$time = $SofortLib_ClassicNotification->getTime();
	$time = strftime('%Y-%m-%d %H:%M:%S', strtotime($time));
	$statusReason = $SofortLib_ClassicNotification->getStatusReason();
	$status = $SofortLib_ClassicNotification->getStatus();
	$xOrderId = $SofortLib_ClassicNotification->getUserVariable(0);
	$xCustomerId = $SofortLib_ClassicNotification->getUserVariable(1);
	
	$paymentMethod = 'ideal';
} elseif ($_GET['action'] == 'su') { //su-classic
	//su-classic
} else { //multipay
	$SofortLib_Notification = new SofortLib_Notification();
	$transactionId = $SofortLib_Notification->getNotification();
	$time = $SofortLib_Notification->getTime();
	$SofortLib_TransactionData = new SofortLib_TransactionData(MODULE_PAYMENT_SOFORT_MULTIPAY_APIKEY);
	$SofortLib_TransactionData->setTransaction($transactionId);
	$SofortLib_TransactionData->sendRequest();
	$paymentMethod = $SofortLib_TransactionData->getPaymentMethod();
}

if (empty($transactionId)) {
	exit('TransID empty!');
}
if (is_object($SofortLib_TransactionData) && $SofortLib_TransactionData instanceof SofortLib_TransactionData) {
	if ($SofortLib_TransactionData->isError()) {
		exit($SofortLib_TransactionData->getError());
	}

	$time = strftime('%Y-%m-%d %H:%M:%S', strtotime($time));
	$statusReason = $SofortLib_TransactionData->getStatusReason();
	$status = $SofortLib_TransactionData->getStatus();
	$xOrderId = $SofortLib_TransactionData->getUserVariable(0);
	$xCustomerId = $SofortLib_TransactionData->getUserVariable(1);
}

//do something if 'Rechnung by sofort'
if ($paymentMethod == 'sr') {
	$configuration = getPaymentModuleConfiguration();
	$orderStatus = array(
		'unconfirmed' => $configuration['MODULE_PAYMENT_SOFORT_SR_TMP_STATUS_ID'],
		'confirmed' => $configuration['MODULE_PAYMENT_SOFORT_SR_ORDER_STATUS_ID'],
		'cancelled' => $configuration['MODULE_PAYMENT_SOFORT_SR_CANCEL_STATUS_ID'],
		//'credited' => $configuration['MODULE_PAYMENT_SOFORT_SR_CREDITED_STATUS_ID'],
	);

	$PnagInvoice = new PnagInvoice(MODULE_PAYMENT_SOFORT_MULTIPAY_APIKEY, $transactionId);

	if ($PnagInvoice->isError()) {
		$errors = $PnagInvoice->getErrors();
		echo MODULE_PAYMENT_SOFORT_ERROR_TERMINATED.' - '.print_r($errors, true);
		exit;
	}

	$completeInvoiceStatus = $PnagInvoice->getState();
	$orderId = getOrderId($transactionId);
	$lastOrderStatus = getLastOrderStatus($orderId);
	$newTotal = checkIfNewTotal($PnagInvoice, $orderId);

	//update the order-status
	switch($completeInvoiceStatus) {
		case PnagInvoice::PENDING_CONFIRM_INVOICE:	// Offene Rechnung, noch nicht bestaetigt
			updateShopAdresses($SofortLib_TransactionData->getInvoiceAddress(), $SofortLib_TransactionData->getShippingAddress(), $orderId);
			$historyComments = getHistoryComments(PnagInvoice::PENDING_CONFIRM_INVOICE, $transactionId);
			updateOrderStatus($PnagInvoice, $orderId, $orderStatus['unconfirmed'], $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_PENDING: // Rechnung bestaetigt, noch keine Zahlung eingegangen
			$historyComments = getHistoryComments(PnagInvoice::PENDING_NOT_CREDITED_YET_PENDING);
			updateOrderStatus($PnagInvoice, $orderId, $orderStatus['confirmed'], $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::REFUNDED_REFUNDED_REFUNDED: //Kunde und H�ndler wird der Betrag gutgeschrieben
			$historyComments = getHistoryComments(PnagInvoice::REFUNDED_REFUNDED_REFUNDED);
			updateOrderStatus($PnagInvoice, $orderId, $orderStatus['cancelled'], $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::LOSS_CANCELED: //Bestaetigte oder unbestaetigte Bestellung durch Haendler storniert
			$historyComments = getHistoryComments(PnagInvoice::LOSS_CANCELED);
			updateOrderStatus($PnagInvoice, $orderId, $orderStatus['cancelled'], $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::LOSS_CONFIRMATION_PERIOD_EXPIRED: //Bestaetigungszeitraum von 30 Tagen abgelaufen
			$historyComments = getHistoryComments(PnagInvoice::LOSS_CONFIRMATION_PERIOD_EXPIRED);
			updateOrderStatus($PnagInvoice, $orderId, $orderStatus['cancelled'], $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_RECEIVED:   //Kunde hat gezahlt, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::PENDING_NOT_CREDITED_YET_RECEIVED);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::RECEIVED_CREDITED_RECEIVED:          //Kunde hat bezahlt, Betrag an Haendler wurde ausgesch�ttet
			$historyComments = getHistoryComments(PnagInvoice::RECEIVED_CREDITED_RECEIVED);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_1: //Kunde hat erste Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_1);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_1: //Kunde hat erste Mahnung, Betrag an Haendler ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::RECEIVED_CREDITED_REMINDER_1);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_2: //Kunde hat zweite Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_2);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_2: //Kunde hat zweite Mahnung,Betrag an Haendler ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::RECEIVED_CREDITED_REMINDER_2);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_3: //Kunde hat dritte Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_3);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_3: //Kunde hat dritte Mahnung, Betrag an Haendler ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::RECEIVED_CREDITED_REMINDER_3);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_DELCREDERE: //Kunde hat Inkasso, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::PENDING_NOT_CREDITED_YET_DELCREDERE);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::RECEIVED_CREDITED_DELCREDERE: //Kunde hat Inkasso, Betrag an Haendler ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::RECEIVED_CREDITED_DELCREDERE);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		case PnagInvoice::RECEIVED_CREDITED_PENDING:    //Kunde hat bisher nicht bezahlt, Betrag an Haendler ausgeschuettet
			$historyComments = getHistoryComments(PnagInvoice::RECEIVED_CREDITED_PENDING);
			updateOrderStatus($PnagInvoice, $orderId, $lastOrderStatus, $historyComments['customer'], $time, $newTotal);
			break;
		default:
			$historyComments = array();
			$historyComments['customer'] = "";
			$historyComments['seller'] = "";
			echo MODULE_PAYMENT_SOFORT_SR_UNKNOWN_STATUS.' ('.$completeInvoiceStatus.')\n';
			break;
	}

	saveNotificationInSofortTables($PnagInvoice, $orderId, $historyComments['customer'], $historyComments['seller']);
	exit();
} else { //all other payment-methods without sr
	if ($paymentMethod == 'su') {
		$paymentMethodStr = MODULE_PAYMENT_SOFORT_SOFORTUEBERWEISUNG_TEXT_TITLE;
		$tmpOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_SU_TMP_STATUS_ID);
		$confirmedOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_SU_ORDER_STATUS_ID);
	} elseif ($paymentMethod == 'sl') {
		$paymentMethodStr = MODULE_PAYMENT_SOFORT_SOFORTLASTSCHRIFT_TEXT_TITLE;
		$tmpOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_SL_TMP_STATUS_ID);
		$confirmedOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_SL_ORDER_STATUS_ID);
	} elseif ($paymentMethod == 'sv') {
		$paymentMethodStr = MODULE_PAYMENT_SOFORT_SOFORTVORKASSE_TEXT_TITLE;
		$tmpOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_SV_TMP_STATUS_ID);
		$confirmedOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_SV_ORDER_STATUS_ID);
	} elseif ($paymentMethod == 'ls') {
		$paymentMethodStr = MODULE_PAYMENT_SOFORT_LASTSCHRIFT_TEXT_TITLE;
		$tmpOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_LS_TMP_STATUS_ID);
		$confirmedOrderStatus = getStatusId(MODULE_PAYMENT_SOFORT_LS_ORDER_STATUS_ID);
	} elseif ($paymentMethod == 'ideal') {
		$paymentMethodStr = MODULE_PAYMENT_SOFORT_IDEAL_TEXT_TITLE;
		$tmpOrderStatus = getStatusId(MODULE_PAYMENT_PNAG_IDEAL_CLASSIC_TMP_STATUS_ID);
		$confirmedOrderStatus = getStatusId(MODULE_PAYMENT_PNAG_IDEAL_CLASSIC_ORDER_STATUS_ID);
	} else {
		$paymentMethodStr = $paymentMethod;
		$tmpOrderStatus = DEFAULT_ORDERS_STATUS_ID;
		$confirmedOrderStatus = DEFAULT_ORDERS_STATUS_ID;
	}

	if ($statusReason == 'not_credited_yet') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_NOT_CREDITED_YET;
	} elseif ($statusReason == 'wait_for_money' && $paymentMethod == 'sv') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_WAIT_FOR_MONEY;
	} elseif ($statusReason == 'credited') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_RECEIVED;
	} elseif ($status == 'loss' && $paymentMethod == 'su') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_SU_LOSS;
	} elseif ($status == 'loss' && $paymentMethod == 'sv') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_SV_LOSS;
	} elseif ($status == 'loss' && $paymentMethod == 'sl') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_DEBIT_RETURNED;
	} elseif ($status == 'loss' && $paymentMethod == 'ls') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_DEBIT_RETURNED;
	} elseif ($statusReason == 'refunded') {
		$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_REFUNDED;
	} else {
		exit(MODULE_PAYMENT_SOFORT_ERROR_UNEXPECTED_STATUS." (".$status.") (".$statusReasonStr.")");
		//$statusReasonStr = MODULE_PAYMENT_SOFORT_STATUS_DEFAULT;
	}

	$orderQuery = xtc_db_query("SELECT orders_status, currency_value, orders_id FROM ".HelperFunctions::escapeSql(TABLE_ORDERS)." WHERE orders_ident_key = '".HelperFunctions::escapeSql($transactionId)."'");

	//not found with transaction-id, search again with order-id and user-id
	if (xtc_db_num_rows($orderQuery) != 1 || empty($transactionId)) {
		$orderQuery = xtc_db_query("SELECT orders_status, currency_value, orders_id FROM ".HelperFunctions::escapeSql(TABLE_ORDERS)." WHERE orders_id = '".(int)$xOrderId."' AND customers_id = '".(int)$xCustomerId."'");
	}

	if (xtc_db_num_rows($orderQuery) != 1) {
		echo MODULE_PAYMENT_SOFORT_ERROR_ORDER_NOT_FOUND.' '.$xOrderId.' '.$transactionId;
	} else {
		$order = xtc_db_fetch_array($orderQuery);

		if ((int)$xOrderId != (int)$order['orders_id']) {
			echo MODULE_PAYMENT_SOFORT_ERROR_ORDER_NOT_FOUND.' '.$xOrderId.' : '.$order['orders_id'].' '.$transactionId;
			exit();
		}

		$totalQuery = xtc_db_query("SELECT value FROM ".HelperFunctions::escapeSql(TABLE_ORDERS_TOTAL)." WHERE orders_id = '".(int)$xOrderId."' AND class = 'ot_total' LIMIT 1");
		$total = xtc_db_fetch_array($totalQuery);
		$orderTotal = number_format($total['value'] , 2, '.', '');

		//transaction successfully created
		if ($status == 'pending') {
			if ($paymentMethod == 'sv') {
				$orderStatus = $tmpOrderStatus;
			} else {
				$orderStatus = $confirmedOrderStatus;
			}

			$comment = $statusReasonStr;
			echo MODULE_PAYMENT_SOFORT_SUCCESS_CALLBACK;
		} elseif ($status == 'received') {
			// money received
			$orderStatus = $confirmedOrderStatus;
			$comment = $statusReasonStr;
			echo MODULE_PAYMENT_SOFORT_SUCCESS_CALLBACK;
		} elseif ($status == 'loss') {
			// money not received
			$orderStatus = $tmpOrderStatus;
			$comment = $statusReasonStr;
			echo MODULE_PAYMENT_SOFORT_SUCCESS_CALLBACK;
		} elseif ($status == 'refunded') {
			// refund
			$orderStatus = $tmpOrderStatus;
			$comment = $statusReasonStr;
			echo MODULE_PAYMENT_SOFORT_SUCCESS_CALLBACK;
		} else {
			// something went wrong
			$orderStatus = $tmpOrderStatus;
			$comment = MODULE_PAYMENT_SOFORT_ERROR_UNEXPECTED_STATUS." ".$status." ".$statusReasonStr;
			echo MODULE_PAYMENT_SOFORT_ERROR_UNEXPECTED_STATUS;
		}

		$tId = $transactionId;  //needed for replacement in following line
		$comment = preg_replace('#\{\{([a-zA-Z0-9_]+)\}\}#e', '$$1', $comment); //set paymentMethod, tId and time

		if ($_GET['action'] == 'ideal') { //ideal: set TransactionID to history
			$sqlDataArray = array(
				'orders_id' => (int)$xOrderId,
				'orders_status_id' => $tmpOrderStatus,
				'date_added' => 'sqlcommand:now()',
				'customer_notified' => HelperFunctions::getIniValue('sofortCustomerNotified'),
				'comments' => MODULE_PAYMENT_SOFORT_MULTIPAY_TRANSACTION_ID.': '.$transactionId,
			);
			xtc_db_query(HelperFunctions::getEscapedInsertInto(TABLE_ORDERS_STATUS_HISTORY, $sqlDataArray));
			// Update ideal-status
			$sqlDataArray = array(
				'orders_id' => (int)$xOrderId,
				'orders_status_id' => $orderStatus,
				'date_added' => 'sqlcommand:now()',
				'customer_notified' => HelperFunctions::getIniValue('sofortCustomerNotified'),
				'comments' => addslashes ($comment),
			);
			xtc_db_query(HelperFunctions::getEscapedInsertInto(TABLE_ORDERS_STATUS_HISTORY, $sqlDataArray));
			xtc_db_query("UPDATE ".HelperFunctions::escapeSql(TABLE_ORDERS)." SET orders_status = '".HelperFunctions::escapeSql($orderStatus)."', last_modified = NOW() WHERE orders_id = '".(int)$xOrderId."'");
		} else {
			// Update status
			$sqlDataArray = array(
				'orders_id' => (int)$xOrderId,
				'orders_status_id' => $orderStatus,
				'date_added' => 'sqlcommand:now()',
				'customer_notified' => HelperFunctions::getIniValue('sofortCustomerNotified'),
				'comments' => addslashes($comment),
			);
			xtc_db_query(HelperFunctions::getEscapedInsertInto(TABLE_ORDERS_STATUS_HISTORY, $sqlDataArray));
			xtc_db_query("UPDATE ".HelperFunctions::escapeSql(TABLE_ORDERS)." SET orders_status = '".HelperFunctions::escapeSql($orderStatus)."', last_modified = NOW() WHERE orders_id = '".(int)$xOrderId."'");
		}
	}
}


//////////////////////////////////////////////
//// from here only functions following  /////
//////////////////////////////////////////////


function updateShopAdresses ($invoiceAddress, $shippingAddress, $orderId) {
	global $shopEncoding;
	if (!$orderId) {
		echo "No order_id given to function updateShopAdresses(). Exit!";
		exit();
	}

	xtc_db_query("	UPDATE	".HelperFunctions::escapeSql(TABLE_ORDERS)." 
					SET		billing_name = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['firstname'],2))." ".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['lastname'],2))."',
							billing_firstname = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['firstname'],2))."',
							billing_lastname = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['lastname'],2))."', 
							billing_street_address = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['street'],2))." ".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['street_number'],2))."', 
							billing_city = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['city'],2))."', 
							billing_postcode = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($invoiceAddress['zipcode'],2))."', 
							billing_state = '', 
							billing_company = '', 
							last_modified = now() 
					WHERE	orders_id = '".(int)$orderId."'");
	xtc_db_query("	UPDATE	".HelperFunctions::escapeSql(TABLE_ORDERS)."
					SET		delivery_name = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['firstname'],2))." ".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['lastname'],2))."',
							delivery_firstname = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['firstname'],2))."', 
							delivery_lastname = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['lastname'],2))."', 
							delivery_street_address = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['street'],2))." ".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['street_number'],2))."', 
							delivery_city = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['city'],2))."', 
							delivery_postcode = '".HelperFunctions::escapeSql(helperFunctions::convertEncoding($shippingAddress['zipcode'],2))."', 
							delivery_company = '', 
							delivery_state = '', 
							last_modified = now() 
					WHERE	orders_id = '".(int)$orderId."'");
	echo MODULE_PAYMENT_SOFORT_SR_SUCCESS_ADDRESS_UPDATED."\n";
}


function getStatusId ($status) {
	if ($status > 0) {
		return $status;
	} else {
		return DEFAULT_ORDERS_STATUS_ID;
	}
}


/**
 *
 * Update the order status and the order status history in database
 * @param int $orderId
 * @param array $status
 * @param string $comment
 */
function updateOrderStatus($PnagInvoice, $orderId, $status, $comment, $time, $newTotal) {
	if (!$orderId) {
		echo "No order_id given to function updateOrderStatus(). Exit!";
		exit();
	}

	if ($newTotal) {
		insertNewTotalCommentToHistory($orderId, $status, $time, $newTotal);
	}

	$completeInvoiceStatus = $PnagInvoice->getState();

	if (!commentIsValid($orderId, $completeInvoiceStatus)) {
		echo MODULE_PAYMENT_SOFORT_SR_STATUSUPDATE_UNNECESSARY;
		return;
	}

	xtc_db_query('UPDATE '.HelperFunctions::escapeSql(TABLE_ORDERS).' SET orders_status = "'.HelperFunctions::escapeSql($status).'", last_modified = now() WHERE orders_id = '.(int)$orderId.';');
	$sqlDataArray = array(
		'orders_id' => (int)$orderId,
		'orders_status_id' => $status,
		'date_added' => 'sqlcommand:now()',
		'customer_notified' => HelperFunctions::getIniValue('sofortCustomerNotified'),
		'comments' => $comment.' '.MODULE_PAYMENT_SOFORT_SR_TRANSLATE_TIME.': '.$time,
	);
	xtc_db_query(HelperFunctions::getEscapedInsertInto(TABLE_ORDERS_STATUS_HISTORY, $sqlDataArray));
	echo MODULE_PAYMENT_SOFORT_SUCCESS_CALLBACK;
}


/**
 *
 * Check, if it makes sense, to show the comment in CUSTOMER-history (in comparison with the previous comment/invoiceStatus)
 * @param string $orderId
 * @param string $completeInvoiceStatus
 * @return false - dont show the comment in customer-history ELSE true
 */
function commentIsValid($orderId, $completeInvoiceStatus){
	$lastShopStatusId = HelperFunctions::getLastStatusIdFromSofortTable($orderId);

	//check, if its the same state
	if ($lastShopStatusId == $completeInvoiceStatus) {
		return false;
	}

	switch($completeInvoiceStatus) {
		case PnagInvoice::PENDING_CONFIRM_INVOICE:	// Offene Rechnung, noch nicht bestaetigt
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_PENDING: // Rechnung bestaetigt, noch keine Zahlung eingegangen
			break;
		case PnagInvoice::REFUNDED_REFUNDED_REFUNDED: //Kunde und H�ndler wird der Betrag gutgeschrieben
			break;
		case PnagInvoice::LOSS_CANCELED: //Unbestaetigte Rechnung durch Haendler storniert
			break;
		case PnagInvoice::LOSS_CONFIRMATION_PERIOD_EXPIRED: //Bestaetigungszeitraum von 30 Tagen abgelaufen
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_RECEIVED:   //Kunde hat gezahlt, Betrag an Haendler noch nicht ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::RECEIVED_CREDITED_RECEIVED) {
				return false;
			}

			break;
		case PnagInvoice::RECEIVED_CREDITED_RECEIVED:          //Kunde hat bezahlt, Betrag an Haendler wurde ausgesch�ttet
			if ($lastShopStatusId == PnagInvoice::PENDING_NOT_CREDITED_YET_RECEIVED) {
				return false;
			}

			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_1: //Kunde hat erste Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::RECEIVED_CREDITED_REMINDER_1) {
				return false;
			}

			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_1: //Kunde hat erste Mahnung, Betrag an Haendler ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_1) {
				return false;
			}

			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_2: //Kunde hat zweite Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::RECEIVED_CREDITED_REMINDER_2) {
				return false;
			}

			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_2: //Kunde hat zweite Mahnung,Betrag an Haendler ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_2) {
				return false;
			}

			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_3: //Kunde hat dritte Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::RECEIVED_CREDITED_REMINDER_3) {
				return false;
			}

			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_3: //Kunde hat dritte Mahnung, Betrag an Haendler ausgeschuettet
			if($lastShopStatusId == PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_3) {
				return false;
			}

			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_DELCREDERE: //Kunde hat Inkasso, Betrag an Haendler noch nicht ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::RECEIVED_CREDITED_DELCREDERE) {
				return false;
			}

			break;
		case PnagInvoice::RECEIVED_CREDITED_DELCREDERE: //Kunde hat Inkasso, Betrag an Haendler ausgeschuettet
			if ($lastShopStatusId == PnagInvoice::PENDING_NOT_CREDITED_YET_DELCREDERE) {
				return false;
			}

			break;
		case PnagInvoice::RECEIVED_CREDITED_PENDING:    //Kunde hat bisher nicht bezahlt, Betrag an Haendler ausgeschuettet
			return false; //never a customernotification with this state needed
			break;
		default:
			break;
	}

	return true;
}


/**
 * Fetch order-ID
 * @param $transactionId
 */
function getOrderId($transactionId) {
	if (!$transactionId) {
		echo "No Transaction-ID given to function getOrderId(). Exit!";
		exit();
	}

	$sql = 'SELECT orders_id FROM '.TABLE_ORDERS.' WHERE orders_ident_key = "'.$transactionId.'"';
	$orderId = xtc_db_query($sql);
	$orderId = xtc_db_fetch_array($orderId);
	return $orderId['orders_id'];
}


/**
 * Fetch the module's configuration
 * @return Array $configurationArray
 */
function getPaymentModuleConfiguration() {
	$sql = 'SELECT configuration_key, configuration_value FROM configuration WHERE configuration_key LIKE "%MODULE_PAYMENT_SOFORT_SR%"';
	$configurationQuery = xtc_db_query($sql);
	$configurationArray = array();

	while ($configurationData = xtc_db_fetch_array($configurationQuery)) {
		$configurationArray[$configurationData['configuration_key']] = $configurationData['configuration_value'];
	}

	return $configurationArray;
}


function insertNewTotalCommentToHistory($orderId, $status, $time, $newTotal){
	$sqlDataArray = array(
		'orders_id' => (int)$orderId,
		'orders_status_id' => $status,
		'date_added' => 'sqlcommand:now()',
		'customer_notified' => HelperFunctions::getIniValue('sofortCustomerNotified'),
		'comments' => MODULE_PAYMENT_SOFORT_SR_TRANSLATE_CART_EDITED.' '.MODULE_PAYMENT_SOFORT_SR_TRANSLATE_CURRENT_TOTAL.' '.$newTotal.' Euro '.MODULE_PAYMENT_SOFORT_SR_TRANSLATE_TIME.': '.$time,
	);
	xtc_db_query(HelperFunctions::getEscapedInsertInto(TABLE_ORDERS_STATUS_HISTORY, $sqlDataArray));
	echo MODULE_PAYMENT_SOFORT_SR_TRANSLATE_CART_EDITED."\n";
}


function checkIfNewTotal($PnagInvoice, $orderId){
	$lastShopTotal = HelperFunctions::getLastAmountFromSofortTable($orderId);
	$pnagTotal = $PnagInvoice->getAmount();

	//if no notification exists in sofort-table, we ignore this
	if (!$lastShopTotal) {
		return false;
	}

	if ($lastShopTotal != $pnagTotal) {
		return $pnagTotal;
	}

	return false;
}


/**
 * save SR-orders in our sofort-tables
 * Enter description here ...
 * @param PnagInvoice $PnagInvoice
 * @param Int $xOrderId
 */
function saveNotificationInSofortTables($PnagInvoice, $orderId, $customerComment, $sellerComment){
	$query = xtc_db_query('SELECT id FROM sofort_orders WHERE orders_id = '.$orderId);
	$result = xtc_db_fetch_array($query);
	$sofortOrdersId = $result['id'];

	//save the transdata in our sofort-tables
	HelperFunctions::insertSofortOrdersNotification($sofortOrdersId, $PnagInvoice, $customerComment, $sellerComment);
}


/**
 * return the last orderState for the given orderId from table orders (NOT from sofort-tables!)
 */
function getLastOrderStatus($orderId){

	if (!$orderId) {
		echo "No Order-ID given to function getLastOrderStatus(). Exit!";
		exit();
	}

	$sql = 'SELECT orders_status FROM '.TABLE_ORDERS.' WHERE orders_id = "'.$orderId.'"';
	$orderStatus = xtc_db_query($sql);
	$orderStatus = xtc_db_fetch_array($orderStatus);
	return $orderStatus['orders_status'];
}

/**
 * Build for the given $invoiceStatus the history-comments for the customer and seller
 * @return array Comments for the customer and seller
 */
function getHistoryComments($invoiceStatus, $transactionId = ''){
	
	$historyComments = array();
	
	switch($invoiceStatus){
		case PnagInvoice::PENDING_CONFIRM_INVOICE:	// Offene Rechnung, noch nicht bestaetigt
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_PENDINIG_NOT_CONFIRMED_COMMENT.$transactionId;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_PENDINIG_NOT_CONFIRMED_COMMENT.$transactionId;
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_PENDING: // Rechnung bestaetigt, noch keine Zahlung eingegangen
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CONFIRMED;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CONFIRMED_SELLER;
			break;
		case PnagInvoice::REFUNDED_REFUNDED_REFUNDED: //Kunde und H�ndler wird der Betrag gutgeschrieben
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CANCELED_REFUNDED;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CANCELED_REFUNDED_SELLER;
			break;
		case PnagInvoice::LOSS_CANCELED: //Unbestaetigte Rechnung durch Haendler storniert
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CANCELED;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CANCELED;
			break;
		case PnagInvoice::LOSS_CONFIRMATION_PERIOD_EXPIRED: //Bestaetigungszeitraum von 30 Tagen abgelaufen
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CANCEL_30_DAYS;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_CANCEL_30_DAYS;
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_RECEIVED:   //Kunde hat gezahlt, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_RECEIVED;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_PENDING_NOT_CREDITED_YET_RECEIVED_SELLER;
			break;
		case PnagInvoice::RECEIVED_CREDITED_RECEIVED:          //Kunde hat bezahlt, Betrag an Haendler wurde ausgesch�ttet
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_RECEIVED;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_RECEIVED_CREDITED_RECEIVED_SELLER;
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_1: //Kunde hat erste Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments['customer'] = str_replace('{{d}}', '1', MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_REMINDER);
			$historyComments['seller'] = str_replace('{{d}}', '1', MODULE_PAYMENT_SOFORT_SR_PENDING_NOT_CREDITED_YET_REMINDER_SELLER);
			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_1: //Kunde hat erste Mahnung, Betrag an Haendler ausgeschuettet
			$historyComments['customer'] = str_replace('{{d}}', '1', MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_REMINDER);
			$historyComments['seller'] = str_replace('{{d}}', '1', MODULE_PAYMENT_SOFORT_SR_RECEIVED_CREDITED_REMINDER_SELLER);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_2: //Kunde hat zweite Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments['customer'] = str_replace('{{d}}', '2', MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_REMINDER);
			$historyComments['seller'] = str_replace('{{d}}', '2', MODULE_PAYMENT_SOFORT_SR_PENDING_NOT_CREDITED_YET_REMINDER_SELLER);
			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_2: //Kunde hat zweite Mahnung,Betrag an Haendler ausgeschuettet
			$historyComments['customer'] = str_replace('{{d}}', '2', MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_REMINDER);
			$historyComments['seller'] = str_replace('{{d}}', '2', MODULE_PAYMENT_SOFORT_SR_RECEIVED_CREDITED_REMINDER_SELLER);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_REMINDER_3: //Kunde hat dritte Mahnung, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments['customer'] = str_replace('{{d}}', '3', MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_REMINDER);
			$historyComments['seller'] = str_replace('{{d}}', '3', MODULE_PAYMENT_SOFORT_SR_PENDING_NOT_CREDITED_YET_REMINDER_SELLER);
			break;
		case PnagInvoice::RECEIVED_CREDITED_REMINDER_3: //Kunde hat dritte Mahnung, Betrag an Haendler ausgeschuettet
			$historyComments['customer'] = str_replace('{{d}}', '3', MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_REMINDER);
			$historyComments['seller'] = str_replace('{{d}}', '3', MODULE_PAYMENT_SOFORT_SR_RECEIVED_CREDITED_REMINDER_SELLER);
			break;
		case PnagInvoice::PENDING_NOT_CREDITED_YET_DELCREDERE: //Kunde hat Inkasso, Betrag an Haendler noch nicht ausgeschuettet
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_DELCREDERE;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_PENDING_NOT_CREDITED_YET_DELCREDERE_SELLER;
			break;
		case PnagInvoice::RECEIVED_CREDITED_DELCREDERE: //Kunde hat Inkasso, Betrag an Haendler ausgeschuettet
			$historyComments['customer'] = MODULE_PAYMENT_SOFORT_SR_TRANSLATE_INVOICE_DELCREDERE;
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_RECEIVED_CREDITED_DELCREDERE_SELLER;
			break;
		case PnagInvoice::RECEIVED_CREDITED_PENDING:    //Kunde hat bisher nicht bezahlt, Betrag an Haendler ausgeschuettet
			$historyComments['customer'] = '';
			$historyComments['seller'] = MODULE_PAYMENT_SOFORT_SR_RECEIVED_CREDITED_PENDING_SELLER;
			break;
		//should never happen...
		default:
			$historyComments['customer'] = '';
			$historyComments['seller'] = '';
			break;
	}
	
	return $historyComments;
}
